﻿/**************************************************************
 * Copyright gt1987. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/4/19 11:22:04
 * Description: BusnessExceptionFilterAttribute
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using gt.dotnetcore.webapi.extensions.ApiResults;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace gt.dotnetcore.webapi.extensions.ApiException
{
    /// <summary>
    /// 业务异常拦截器
    /// 用于拦截BusnessException，针对性返回Result
    /// 如果有其它的ExceptionFilter，要注意执行顺序。一般可以把逻辑集成到一个ExceptionFilter
    /// </summary>
    public class BusinessExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public BusinessExceptionFilterAttribute()
        {
        }

        public override void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            if (ex is BusinessException)
            {
                BusinessException realEx = (BusinessException)ex;
                context.Result = new ErrorResult(realEx.Code, realEx.Msg);
            }
            else
            {
                context.ExceptionHandled = false;
            }
        }
    }

    /// <summary>
    /// 业务异常
    /// </summary>
    public class BusinessException : Exception
    {
        public BusinessException(int code, string msg)
        {
            Code = code;
            Msg = msg;
        }

        public int Code { get; private set; }
        public string Msg { get; private set; }
    }
}
